import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { request } from '@/utils/request'

export interface User {
  id: number
  username: string
  fullName: string
  roleName: string
  permissions: string[]
  lastLoginAt?: string
  createdAt?: string
}

export interface LoginForm {
  username: string
  password: string
}

export const useAuthStore = defineStore('auth', () => {
  // 从localStorage恢复用户信息
  const getStoredUser = (): User | null => {
    try {
      const storedUser = localStorage.getItem('admin_user')
      return storedUser ? JSON.parse(storedUser) : null
    } catch (error) {
      console.error('解析存储的用户信息失败:', error)
      localStorage.removeItem('admin_user')
      return null
    }
  }

  // 状态
  const token = ref<string>(localStorage.getItem('admin_token') || '')
  const user = ref<User | null>(getStoredUser())
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!user.value)
  const hasPermission = computed(() => (permission: string) => {
    if (!user.value) return false
    const permissions = user.value.permissions || []
    return permissions.includes('*') || permissions.includes(permission)
  })

  // 登录
  const login = async (loginForm: LoginForm) => {
    loading.value = true
    try {
      const response = await request.post<{
        success: boolean
        data: {
          token: string
          user: User
        }
        message: string
      }>('/auth/login', loginForm)

      if (response.success) {
        token.value = response.data.token
        user.value = response.data.user

        // 保存token和用户信息到localStorage
        localStorage.setItem('admin_token', token.value)
        localStorage.setItem('admin_user', JSON.stringify(response.data.user))

        return response
      } else {
        throw new Error(response.message)
      }
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return null

    try {
      const response = await request.get<{
        success: boolean
        data: User
      }>('/auth/profile')

      if (response.success) {
        user.value = response.data
        // 更新localStorage中的用户信息
        localStorage.setItem('admin_user', JSON.stringify(response.data))
        return response.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，清除token
      logout()
      return null
    }
  }

  // 更新用户信息
  const updateProfile = async (updateData: Partial<User> & { old_password?: string; new_password?: string }) => {
    loading.value = true
    try {
      const response = await request.put<{
        success: boolean
        data: User
        message: string
      }>('/auth/profile', updateData)

      if (response.success) {
        user.value = response.data
        // 更新localStorage中的用户信息
        localStorage.setItem('admin_user', JSON.stringify(response.data))
        return response
      } else {
        throw new Error(response.message)
      }
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      if (token.value) {
        await request.post('/auth/logout')
      }
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      // 清除本地状态
      token.value = ''
      user.value = null
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_user')
    }
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      const response = await request.post<{
        success: boolean
        data: { token: string }
      }>('/auth/refresh')

      if (response.success) {
        token.value = response.data.token
        localStorage.setItem('admin_token', token.value)
        return response.data.token
      }
    } catch (error) {
      console.error('刷新token失败:', error)
      logout()
      return null
    }
  }

  // 初始化（应用启动时调用）
  const initialize = async () => {
    if (token.value) {
      await fetchUserInfo()
    }
  }

  return {
    // 状态
    token,
    user,
    loading,

    // 计算属性
    isLoggedIn,
    hasPermission,

    // 方法
    login,
    logout,
    fetchUserInfo,
    updateProfile,
    refreshToken,
    initialize
  }
})

export default useAuthStore
